package cc.vv.lkbasecomponent.util;

import android.app.ActivityManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.drawable.Drawable;
import android.location.LocationManager;
import android.media.AudioManager;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
import android.os.Vibrator;

import java.util.List;

import cc.vv.lkbasecomponent.base.app.LKBaseApplication;
import cc.vv.lklibrary.log.LogOperate;

/**
 * App系统,运行,相关工具
 *
 * @author Zml
 * @date 2018/3/9
 */

public class LKSystemUtil {

    private static long mLastNotifiyTime;
    private static AudioManager mAudioManager;
    private static Vibrator mVibrator;
    private static Ringtone mRingtone = null;

    /**
     * 判断GPS是否开启，GPS或者AGPS开启一个就认为是开启的
     *
     * @return true 表示开启
     */
    public static boolean isOPenGPS() {
        LocationManager locationManager = (LocationManager)
                LKBaseApplication.getApplication().getSystemService(Context.LOCATION_SERVICE);
        assert locationManager != null;
        // 通过WLAN或移动网络(3G/2G)确定的位置（也称作AGPS，辅助GPS定位。主要用于在室内或遮盖物（建筑群或茂密的深林等）密集的地方定位）
        return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
    }

    /**
     * 程序是否在前台运行
     *
     * @return
     */
    public static boolean isAppOnForeground() {
        ActivityManager activityManager = (ActivityManager) LKBaseApplication.getApplication()
                .getApplicationContext().getSystemService(Context.ACTIVITY_SERVICE);
        String packageName = LKBaseApplication.getApplication().getApplicationContext().getPackageName();
        List<ActivityManager.RunningAppProcessInfo> appProcesses = activityManager
                .getRunningAppProcesses();
        if (appProcesses == null) {
            return false;
        }

        for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses) {
            if (appProcess.processName.equals(packageName)
                    && appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                return true;
            }
        }
        return false;
    }

    /**
     * 判断程序是否正在后台运行
     *
     * @return
     */
    public static boolean isAppOnBackground() {
        ActivityManager activityManager = (ActivityManager) LKBaseApplication.getApplication()
                .getApplicationContext().getSystemService(Context.ACTIVITY_SERVICE);
        String packageName = LKBaseApplication.getApplication().getApplicationContext().getPackageName();
        if (activityManager == null) {
            return false;
        }
        List<ActivityManager.RunningTaskInfo> processList = activityManager.getRunningTasks(100);
        for (ActivityManager.RunningTaskInfo info : processList) {
            if (info.topActivity.getPackageName().startsWith(packageName)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 检测APK是否存在
     *
     * @return
     */
    public static boolean checkPackage() {
        boolean flag = false;
        try {
            PackageManager packageManager = LKBaseApplication.getApplication().getPackageManager();
            String packageName = LKBaseApplication.getApplication().getApplicationContext().getPackageName();
            PackageInfo packageInfo = packageManager.getPackageInfo(packageName, 0);
            if (null != packageInfo) {
                flag = true;
            }
        } catch (PackageManager.NameNotFoundException e) {
            flag = false;
            e.printStackTrace();
        }
        return flag;
    }

    /**
     * 打开App
     */
    public static void openApp() {
        try {
            String packageName = LKBaseApplication.getApplication().getApplicationContext().getPackageName();
            PackageManager packageManager = LKBaseApplication.getApplication().getPackageManager();
            PackageInfo packageInfo = packageManager.getPackageInfo(packageName, 0);
            Intent resolveIntent = new Intent(Intent.ACTION_MAIN, null);
            resolveIntent.addCategory(Intent.CATEGORY_LAUNCHER);
            resolveIntent.setPackage(packageInfo.packageName);
            List<ResolveInfo> apps = packageManager.queryIntentActivities(resolveIntent, 0);

            ResolveInfo ri = apps.iterator().next();
            if (ri != null) {
                String className = ri.activityInfo.name;

                Intent intent = new Intent(Intent.ACTION_MAIN);
                intent.addCategory(Intent.CATEGORY_LAUNCHER);

                ComponentName cn = new ComponentName(packageName, className);

                intent.setComponent(cn);
                LKBaseApplication.getApplication().startActivity(intent);
            }
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
    }


    /**
     * 获取版本号
     */
    public static int checkVersionCode() {
        PackageManager packageManager = LKBaseApplication.getApplication().getPackageManager();
        try {
            PackageInfo packInfo = packageManager.getPackageInfo(LKBaseApplication.getApplication().getPackageName(), 0);
            return packInfo.versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return 0;
    }

    /**
     * 获取版本信息
     */
    public static String checkVersionInfo() {
        PackageManager packageManager = LKBaseApplication.getApplication().getPackageManager();
        try {
            PackageInfo packInfo = packageManager.getPackageInfo(LKBaseApplication.getApplication().getPackageName(), 0);
            return packInfo.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 获取安装包中logo
     *
     * @param apkPath
     * @return
     */
    public static Drawable getApkIcon(String apkPath) {
        PackageManager pm = LKBaseApplication.getApplication().getPackageManager();
        PackageInfo info = pm.getPackageArchiveInfo(apkPath, PackageManager.GET_ACTIVITIES);
        if (null != info) {
            ApplicationInfo applicationInfo = info.applicationInfo;
            applicationInfo.sourceDir = apkPath;
            applicationInfo.publicSourceDir = apkPath;
            try {
                return pm.getApplicationIcon(applicationInfo);
            } catch (OutOfMemoryError e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    /**
     * 获取APP包名
     *
     * @return
     */
    public static String getAppName() {
        int pid = android.os.Process.myPid();
        String processName = null;
        ActivityManager am = (ActivityManager) LKBaseApplication.getApplication().getSystemService(Context.ACTIVITY_SERVICE);
        assert am != null;
        List l = am.getRunningAppProcesses();
        for (Object aL : l) {
            ActivityManager.RunningAppProcessInfo info = (ActivityManager.RunningAppProcessInfo) (aL);
            try {
                if (info.pid == pid) {
                    processName = info.processName;
                    return processName;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    /**
     * 震动和声音
     */
    public static void vibrateAndPlayTone(Context context) {
        // 5秒内收到新消息,跳过播放铃声
        if (System.currentTimeMillis() - mLastNotifiyTime < 5000) {
            return;
        }
        try {
            if (null == mAudioManager) {
                mAudioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
            }
            if (null == mVibrator) {
                mVibrator = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
            }
            mLastNotifiyTime = System.currentTimeMillis();
            if (mAudioManager.getRingerMode() == AudioManager.RINGER_MODE_SILENT) {
                LogOperate.e("当前为静音模式");
                return;
            }
            //震动
            long[] pattern = new long[]{0, 180, 80, 120};
            mVibrator.vibrate(pattern, -1);
            //铃声 TYPE_NOTIFICATION
            if (mRingtone == null) {
                Uri notificationUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
                mRingtone = RingtoneManager.getRingtone(context, notificationUri);
                if (mRingtone == null) {
                    LogOperate.e("没有找到铃声===" + notificationUri.getPath());
                    return;
                }
            }
            if (!mRingtone.isPlaying()) {
                String vendor = Build.MANUFACTURER;
                mRingtone.play();
                // samsung S3 Bug处理需要添加
                if (vendor != null && vendor.toLowerCase().contains("samsung")) {
                    Thread ctlThread = new Thread() {
                        @Override
                        public void run() {
                            try {
                                if (mRingtone.isPlaying()) {
                                    mRingtone.stop();
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    };
                    ctlThread.run();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
